import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Scanner;

/**
 * Main.
 * 
 * @author Ken "David" McClain
 * @author Peter Mosher
 * @version 1
 */
public class Main {
	
	/** For reading input from the command-line. */
	private final static Scanner console = new Scanner(System.in);
	
	/**
	 * Simplified System.out.print.
	 * This is much easier to type than the whole "System.out.print".
	 * 
	 * @param txt The text to print.
	 */
	private static void p(final Object txt) {
		System.out.print(txt);
	}
	
	
	/**
	 * Main method: where the magic happens.
	 * 
	 * @param args Arguments sent from command-line.
	 */
	public static void main(final String[] args) {
		
		p("\n\n        Whirling Dervishes' Web Spider.");
		p(  "\n        TCSS 422 Operating Systems - Project 2");
		p("\n\n\n");
		
		int PAGE_LIMIT = 0;
		String SEED_URL = ""; // "http://faculty.washington.edu/gmobus/"; //"http://www.reddit.com/r/programming"; // "http://faculty.washington.edu/gmobus/"; // http://news.ycombinator.com/ 
		String[] KEYWORDS = new String[] { }; // "intelligence", "artificial", "agent", "university", "research", "science", "robot"};
		
		// Print help / usage screen if requested in first argument.
		if (args.length > 0) {
			if ("--help".equals(args[0]) || "/?".equals(args[0]) || "-h".equals(args[0]) || "?".equals(args[0])) {
				p("\n\n Usage:");
				p("\n\n java -jar spider.jar <page_limit> <seed_url> <keyword_1> <keyword_2> ... <keyword_10>");
				p("\n\n Example:");
				p("\n java -jar spider.jar 50 http://faculty.washington.edu/gmobus/ intelligence artificial agent university research science robot");
				p("\n");
				return;
			}
		}
		
		// Read arguments from command-line.
		if (args.length > 3) {
			
			// First argument is the page limit
			try {
				PAGE_LIMIT = Integer.parseInt(args[0]);
			} catch (NumberFormatException nfe) { nfe.printStackTrace(); return; };
			
			// Second argument is the seed URL.
			SEED_URL = args[1];
			
			// Third , fourth, fifth, ... arguments are the keywords.
			String temp = args[2];
			for (int i = 3; i < Math.min(args.length, 12); i++) {
				temp += " " + args[i];
			}
			KEYWORDS = temp.split(" ");
		}
		
///////////////////////
		
// Automated MULTITHREADED
		final ModelMulti mm = new ModelMulti();
		//mm.execute(PAGE_LIMIT, SEED_URL, KEYWORDS, 50);
		//System.exit(0);
		
///////////////////////
		
// Automated SINGLE THREADED
		final ModelSingle ms = new ModelSingle();
		//ms.execute(PAGE_LIMIT, SEED_URL, KEYWORDS);
		//System.exit(0);
		
///////////////////////

		p("    * indicates clipboard data has been altered\n");
		p("      data is reverted after first two questions.\n\n");
		
		// Store clip board data.
		Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
		
		// Seed URL question.
		if ("".equals(SEED_URL)) {
			
			// Set the ideal URL to the clipboard.
			Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection("http://faculty.washington.edu/gmobus/"), null);
			
			while ("".equals(SEED_URL)) {
				p("\n*Enter seed URL: ");
				SEED_URL = console.nextLine().trim();
			}
		}
		
		if (!SEED_URL.startsWith("http")) 
			SEED_URL = "http://" + SEED_URL;
		
		// Add a trailing directory separator if needed.
		if (!SEED_URL.endsWith("/") && !SEED_URL.endsWith(".html") && !SEED_URL.endsWith(".htm") && !SEED_URL.endsWith(".txt"))
			SEED_URL += "/";
		
		// Keywords question.
		if (KEYWORDS.length == 0) {
			
			// Set the ideal keywords to the clipboard.
			Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection("intelligence artificial agent university research science robot"), null);
			
			p("\n*Enter keywords separated by spaces (up to 10): ");
			KEYWORDS = console.nextLine().split(" ");
			// Truncate first 10 words.
		}
		
		if (KEYWORDS.length > 10)
			KEYWORDS = Arrays.copyOf(KEYWORDS, 10);
		
		// Restore clip board data.
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(t, null);
		
		// Page limit questions.
		if (PAGE_LIMIT < 1 || PAGE_LIMIT >= 10000) {
			int pageLimit = -1;
			do {
				p("\nEnter maximum number of pages to parse (greater than 0 and less than 10,000): ");
				try {
					pageLimit = Integer.parseInt(console.nextLine());
				} catch (NumberFormatException nfe) { }
			} while (pageLimit < 1 || pageLimit >= 10000);
			PAGE_LIMIT = pageLimit;
		}
		
		// Single vs Multi question.
		String response;
		do {
			p("\nDo you want to run the program as single-threaded? (Y/N): ");
			try {
				response = console.nextLine();
			} catch (NoSuchElementException nse) { response = ""; }
		} while (response.length() == 0 || 
				(response.toLowerCase().charAt(0) != 'n' && 
				 response.toLowerCase().charAt(0) != 'y'));
		
		
		// Start single-threaded implementation.
		if (response.toLowerCase().charAt(0) == 'y') {
			p("\n\n    Single-threaded Web spider\n\n");
			ms.execute(PAGE_LIMIT, SEED_URL, KEYWORDS);
		
		// Start multi-threaded implementation.
		} else {
			
			int max = -1;
			while (max < 1) {
				p("\nEnter the maximum number of threads you want to use: ");
				
				try {
					max = Integer.parseInt(console.nextLine());
				} catch (NumberFormatException nfe) { }
			}
			
			p("\n\n    Starting Multi-threaded Web spider\n\n");
			int NUMBER_OF_THREADS = max;
			mm.execute(PAGE_LIMIT, SEED_URL, KEYWORDS, NUMBER_OF_THREADS);
		}
		
		p("\n\nParsing and retrieving is complete. The program will now exit.\n");
	}
	
}
